<?php

class Admin_ArticlesController extends Zend_Controller_Action {

    public function indexAction() {
        
    }

    public function listAction() {
        $articles = new Content_Model_DbTable_Articles();
        $category = $this->_getParam('category');
        $res = $articles->getList($category);
        $this->_helper->json($res);
    }

    public function singleAction() {
        $articles = new Content_Model_DbTable_Articles();
        $res = $articles->findShort($this->_getParam('id'));
        $this->_helper->json($res->toArray());
    }

    public function saveAction() {
        $data = (array) $this->_getParam('data');
        $id = (int) $data['id'];
        unset($data['id']);
        $articles = new Content_Model_DbTable_Articles();
        $row = ($id === -1) ? $articles->fetchNew() : $articles->find($id)->current();
        $data['text'] = $this->modifiedText($data['_text']);
        $row->setFromArray($data);
        $res = $row->save();
        $this->_helper->json($res);
    }

    public function removeAction() {
        $id = (int) $this->_getParam('id');
        $articles = new Content_Model_DbTable_Articles();
        $row = $articles->find($id)->current();
        $res = $row->delete();
        $this->_helper->json($res);
    }

    public function categoriesAction() {
        $categories = new Content_Model_DbTable_Categories();
        $res = $categories->getShortList();
        $this->_helper->json($res->toArray());
    }
    
    private function modifiedText($text) {
        require 'Markdown/markdown.php';
        return Markdown($text);
    }

}

